package com.hanxiaozhang.threadbase1ndedition.no8fourreference;

import java.lang.ref.PhantomReference;
import java.lang.ref.Reference;
import java.lang.ref.ReferenceQueue;
import java.util.LinkedList;
import java.util.List;

/**
 * 〈一句话功能简述〉<br>
 * 〈虚引用〉
 * <p>
 * 执行前配置堆内存：-Xms20M -Xmx20M
 * <p>
 * 概念：是最弱的一种引用关系，使用PhantomReference类来实现虚引用，主要用来跟踪对象被垃圾回收器回收的活动。
 * <p>
 * 给写JVM用的
 *
 * @author hanxinghua
 * @create 2021/11/18
 * @since 1.0.0
 */
public class No4PhantomReference {

    private static final List<Object> LIST = new LinkedList<>();
    private static final ReferenceQueue<ReferenceObject> QUEUE = new ReferenceQueue<>();


    public static void main(String[] args) {

        PhantomReference<ReferenceObject> phantomReference = new PhantomReference<>(new ReferenceObject(), QUEUE);

        new Thread(() -> {
            while (true) {
                LIST.add(new byte[1024 * 1024]);
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                    Thread.currentThread().interrupt();
                }
                System.out.println(phantomReference.get());
            }
        }).start();

        new Thread(() -> {
            while (true) {
                Reference<? extends ReferenceObject> poll = QUEUE.poll();
                if (poll != null) {
                    System.out.println("--- 虚引用对象被jvm回收了 ---- " + poll);
                }
            }
        }).start();

        try {
            Thread.sleep(500);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

    }
}
